const API_BASE = "https://api.cenguigui.cn/api/duanju/api.php";
const MAX_CONCURRENT_DOWNLOADS = 3; // 同时下载的最大视频数
const DOWNLOAD_HISTORY_KEY = "_download_history"; 
const SEARCH_HISTORY_KEY = "search_history"; 

let webView = new WebView();

//下载变量
let downloadStatus = {};
let globalQueue = []; // 全局下载队列
let activeDownloads = 0; // 当前活跃下载数
let isProcessing = false; // 队列处理状态
let isDownloadCancelled = false;

// 文件访问助手
const fm = FileManager.local();
let bookmarkPath = fm.bookmarkedPath("视频下载") || fm.documentsDirectory();

let requestQueue = [];
let isProcessingQueue = false;
// 异步处理队列的函数
async function processRequestQueue() {
    if (isProcessingQueue) return;
    isProcessingQueue = true;
    
    while (requestQueue.length > 0) {
        const request = requestQueue.shift();
        try {
            await handleScriptableAction(request.action, request.params, webView);
        } catch (error) {
            console.error(`处理请求时出错: ${error}`);
        }
    }
    
    isProcessingQueue = false;
}

//主加载函数
async function main() {
   const htmlContent = 'http://175.178.215.159/drama';
  webView.shouldAllowRequest =  request  => {
        console.log(`Request URL: ${request.url}`); // 调试用
        const url = request.url
        // 允许 http/https 链接正常加载
        if (url.startsWith('http://') || url.startsWith('https://')) {
            return true
        }else if (url.startsWith('mailto:') || 
                url.startsWith('tel:') || 
                url.startsWith('sms:')) {
            return false
        }
        // 捕获自定义Scheme
        if (url.includes('custom://')) {
        // 手动解析URL参数
        const urlParts = request.url.split('?');
        const path = urlParts[0];
        const query = urlParts[1] || '';
        
        // 解析查询参数
        const params = {};
        query.split('&').forEach(pair => {
            const [key, value] = pair.split('=');
            if (key) params[decodeURIComponent(key)] = decodeURIComponent(value || '');
        });
        
        // 提取路径动作
        const action = path.replace('custom://', '').split('/')[1] || '';
        // 处理请求
        requestQueue.push({ action, params});
        // 触发队列处理
        if (!isProcessingQueue) {
            Timer.schedule(0, false, () => {
                processRequestQueue();
            });
        
        }
        return false;
    }
        return true; 
    };
    webView.onDismiss = () => {
        console.log("WebView已关闭，取消所有下载");
        cancelAllDownloads();
        webView = null;
    };
  // 配置WebView
//    await webView.loadURL(htmlContent, bookmarkPath, {
//         allowingReadAccessToURL: bookmarkPath,
//         allowingInsecureHTTPS: true 
//     });
    await webView.loadURL(htmlContent);
    await webView.present(true);
    cancelAllDownloads();
    webView = null;
}

function cancelAllDownloads() {
    // 设置全局取消标志
    isDownloadCancelled = true;
    // 清空下载队列
    globalQueue = [];
    // 重置活动下载计数
    activeDownloads = 0;
    // 更新所有任务状态为取消
    console.log("所有下载任务已取消");
}

// 解析脚本请求
async function handleScriptableAction(action, params, webView) {
    const jsonData = JSON.parse(params.data);
    const bookId = jsonData.bookId;
    const videoId = jsonData.videoId;
    const callbackId = params.callbackId;
    switch(action) {
        case 'download':
            await handleDownload(webView, bookId);
            break;
        case 'playVideo':
            await playVideo(webView,videoId,bookId,callbackId);
            break;
        case 'getBookDownloadStatus':
            await getBookDownloadStatus(webView, bookId,callbackId);
            break;
        case 'delete':
            await deleteBookVideos(webView, bookId,callbackId);
            break;
        case 'getAllDownloadHistory':
            await getAllDownloadHistory(webView,callbackId);
            break;
        case 'getBookInfoDownloadStatus':
            await getBookInfoDownloadStatus(webView, jsonData, callbackId);
            break;
        case 'getSearchHistory':
            await getSearchHistory(webView, callbackId);
            break;
        case 'addSearchHistory':
            addSearchHistory(webView, jsonData, callbackId);
            break;
        case 'addCustomInfo':
            await addCustomInfo(webView, callbackId,jsonData);
            break;
        case 'getCustomsInfo':
            await getCustomsInfo(webView, callbackId,jsonData);
            break;        
    }
}

function sendSuccess(webView, callbackId, data) {
  sendCallback(webView, callbackId, {
    success: true,
    data: data
  });
}

// 发送错误响应
function sendError(webView, callbackId, errorCode, errorMessage) {
  sendCallback(webView, callbackId, {
    success: false,
    code: errorCode,
    error: errorMessage
  });
}

// 发送回调到 WebView（带错误处理）
function sendCallback(webView, callbackId, result) {
  const js = `
    (function() {
      try {
        if (typeof window.__scriptableBridge !== 'undefined' && 
            typeof window.__scriptableBridge.handleCallback === 'function') {
          window.__scriptableBridge.handleCallback(
            '${callbackId}',
            ${JSON.stringify(result)}
          );
        } else {
          // 桥接未初始化，触发错误回调
          if (typeof window.__scriptableBridge !== 'undefined' && 
              typeof window.__scriptableBridge.handleCallbackError === 'function') {
            window.__scriptableBridge.handleCallbackError(
              '${callbackId}',
              'SCRIPTABLE_BRIDGE_NOT_INITIALIZED'
            );
          }
        }
      } catch (jsError) {
        // JavaScript执行错误，触发错误回调
        if (typeof window.__scriptableBridge !== 'undefined' && 
            typeof window.__scriptableBridge.handleCallbackError === 'function') {
          window.__scriptableBridge.handleCallbackError(
            '${callbackId}',
            'JS_EXECUTION_ERROR: ' + jsError.message
          );
        }
      }
    })();
  `;
  let retryCount = 0;
  const evaluate = () => {
    webView.evaluateJavaScript(js).catch(evalError => {
      console.error(`JS执行失败: ${evalError}`);
      if (retryCount < 2) {
        retryCount++;
        setTimeout(evaluate, 500);
      } else {
        console.error(`回调失败: ${callbackId}`, result);
      }
    });
  };
  evaluate();
}

//获取搜索记录
function getSearchHistory(webView,callbackId){
    let history = KeyValueStore.get(SEARCH_HISTORY_KEY);
    if (history) {
        try {
            const a = JSON.parse(history)
            if(callbackId){
                sendSuccess(webView, callbackId, a);
            }
            return a;
        } catch (e) {
            console.log("解析搜索历史记录失败");
            if(callbackId){
                sendError(webView, callbackId, '-1', error.message);
            }
        }
    }
    return [];
}

//添加搜索记录
function addSearchHistory(webView, data,callbackId){
    if(data && data.keyword){
        let history = getSearchHistory(webView, null);
        if (!Array.isArray(history)) {
            history = [];
        }
        const newItem = String(data.keyword);
        if (!history.includes(newItem)) {
            history.unshift(newItem);
        }
        KeyValueStore.set(SEARCH_HISTORY_KEY, JSON.stringify(history));
        sendSuccess(webView, callbackId, history);
    }
}

//视频列表回显是否已下载
function getBookInfoDownloadStatus(webView, data,callbackId){
    let statusMap = {};
    try{
        if(data && data.bookIds){
            for(let i=0;i<data.bookIds.length;i++){
                const bookId = data.bookIds[i];
                const historyRecord = getDownloadHistory(bookId);
                statusMap[bookId] = historyRecord
            }
        }
        sendSuccess(webView, callbackId, statusMap);
    }catch(error){
        console.error(`获取书籍下载状态失败: ${error}`);
        sendError(webView, callbackId, '-1', error.message);
    }
}

//详情回显
async function getBookDownloadStatus(webView, bookId,callbackId) {
    try {
        // 1. 首先检查当前下载状态
        if (downloadStatus[bookId]) {
            const progress = downloadStatus[bookId];
            sendSuccess(webView, callbackId, progress);
            return;
        }
        
        // 2. 检查历史记录
        let historyRecord = getDownloadHistory(bookId);
        if (!historyRecord) {
           historyRecord = {}
        }
        sendSuccess(webView, callbackId, historyRecord);   
    } catch (error) {
        console.error(`详情回显失败: ${error}`);
        sendError(webView, callbackId, '-1', error.message);
    }
}

// 获取书籍信息
async function fetchBookInfo(bookId) {
    const url = `${API_BASE}?book_id=${bookId}&showRawParams=false`;
    const request = new Request(url);
    const response = await request.loadJSON();
    
    if (response.code !== 200) {
        throw new Error(`获取视频失败: ${response.msg}`);
    }
    
    return response;
}

//下载视频开始---》
async function handleDownload(webView, bookId) {
    // 如果书籍已经在下载中，直接返回
    if (downloadStatus[bookId]) {
        console.log(`Book ${bookId} is already in download queue`);
        return;
    }

    // 初始化下载状态
    downloadStatus[bookId] = {
        bookId,
        total: 0,
        completed: 0,
        success: 0,
        failed: 0,
        startDate: new Date().toLocaleString('zh-CN'),
        status: "queued", // 初始状态为排队中
        episodes: []
    };

    // 将任务加入全局队列
    globalQueue.push(bookId);
    
    // 如果队列未处理，启动处理
    if (!isProcessing) {
        processDownloadQueue();
    }
}

async function processDownloadQueue() {
    if (isProcessing || globalQueue.length === 0) return;
    
    isProcessing = true;
    
    while (globalQueue.length > 0) {
         if (isDownloadCancelled) {
            console.log("下载已取消，停止处理队列");
            break;
        }
        const bookId = globalQueue[0]; // 获取队列第一个任务
        
        // 如果当前活跃下载数已达上限，等待
        if (activeDownloads >= MAX_CONCURRENT_DOWNLOADS) {
            await new Promise(resolve => setTimeout(resolve, 500));
            continue;
        }
        
        // 从队列中移除当前任务
        globalQueue.shift();
        // 开始下载当前书籍
        activeDownloads++;
        downloadBook(bookId).finally(() => {
            activeDownloads--;
        });
    }
    
    isProcessing = false;
}

async function downloadBook(bookId) {
     if (isDownloadCancelled) {
        console.log(`下载已取消，跳过书籍 ${bookId}`);
        return;
    }
    const bookStatus = downloadStatus[bookId];
    if (!bookStatus) return;
    
    try {
        bookStatus.status = "downloading";
        await updateBookStatus(bookId);
        // 获取书籍信息
        const bookInfo = await fetchBookInfo(bookId);
        bookStatus.total = bookInfo.data.length;
        bookStatus.title = bookInfo.book_name;
        bookStatus.cover = bookInfo.book_pic;
        bookStatus.category = bookInfo.category;
        bookStatus.desc = bookInfo.desc;
        // 创建目录
        const folderName = `${bookInfo.book_name}_${bookId}`;
        const dir = createBookmarkedFolder(folderName);
        
        // 创建下载队列
        const downloadQueue = [...bookInfo.data];
        const activeTasks = [];
        
        // 处理下一个视频下载
        const downloadNext = async () => {
            if (downloadQueue.length === 0) return;
            
            const item = downloadQueue.shift();
            const episodeIndex = bookInfo.data.indexOf(item);
            
            const task = downloadVideo(bookId, item, episodeIndex, dir);
            activeTasks.push(task);
            
            await task;
            
            // 从活动任务中移除
            const index = activeTasks.indexOf(task);
            if (index !== -1) activeTasks.splice(index, 1);
            
            // 检查是否完成所有下载
            if (bookStatus.completed === bookStatus.total) {
                bookStatus.status = "completed";
                bookStatus.endDate = new Date().toLocaleString('zh-CN');
                await updateBookStatus(bookId);
            }
            
            // 处理队列中的下一个视频
            if (downloadQueue.length > 0) {
                await downloadNext();
            }
        };
        
        // 启动初始下载任务
        const concurrency = Math.min(MAX_CONCURRENT_DOWNLOADS - activeDownloads + 1, downloadQueue.length);
        for (let i = 0; i < concurrency; i++) {
            downloadNext();
        }
        
        // 等待所有活动任务完成
        await Promise.all(activeTasks);
        
    } catch (error) {
        bookStatus.status = "failed";
        bookStatus.error = error.message;
        await updateBookStatus(bookId);
        console.error(`Book ${bookId} download failed: ${error}`);
    } finally {
        // 处理队列中的下一个书籍
        processDownloadQueue();
    }
}

async function downloadVideo(bookId, item, episodeIndex, dir) {
    if (isDownloadCancelled) {
        console.log(`下载已取消，跳过视频 ${item.video_id}`);
        return;
    }
    const bookStatus = downloadStatus[bookId];
    if (!bookStatus) return;
    
    try {
        let videoUrl = `${API_BASE}?video_id=${item.video_id}&type=mp4&level=720p`;
        const fileName = `${item.title}_${item.video_id}.mp4`.replace(/\//g, "-");
        const path = fm.joinPath(dir, fileName);
        
        // 下载视频
        let request = new Request(videoUrl);
        request.headers = {
        ...request.headers,
        "Referer": ""
        };
        let videoData = await request.load();
        
        if (!videoData || videoData.length === 0) {
            videoUrl = `${API_BASE}?video_id=${item.video_id}&type=url`;
            request = new Request(videoUrl);
            videoData = await request.load();
            if (!videoData || videoData.length === 0) {
                throw new Error("下载内容为空");
            }
        }
        
        fm.write(path, videoData);
        
        // 更新状态
        bookStatus.completed++;
        bookStatus.success++;
        bookStatus.episodes[episodeIndex] = {
            title: item.title,
            video_id: item.video_id,
            status: "success",
            path
        };
        
        await updateBookStatus(bookId);
        
    } catch (error) {
        bookStatus.completed++;
        bookStatus.failed++;
        bookStatus.episodes[episodeIndex] = {
            title: item.title,
            video_id: item.video_id,
            status: "failed",
            error: error.message
        };
        
        await updateBookStatus(bookId);
    }
}
//《------下载视频结束
async function updateBookStatus(bookId) {
    const status = downloadStatus[bookId];
    if (!status) return;
    
    // 保存到下载历史
    await addDownloadHistory(status, bookId);
    
    // 更新UI
}

// 播放视频--->
async function playVideo(webView,videoId,bookId = null,callbackId) {
    // 首先检查本地是否有下载
    let localPath = null;
    // 优先使用bookId定位视频
    try{
        if (bookId) {
        // 1. 检查当前下载状态
        if (downloadStatus[bookId]) {
            const episode = downloadStatus[bookId].episodes.find(ep => ep.video_id === videoId);
            if (episode && episode.status === "success") {
                localPath = episode.path;
            }
        }
        
        // 2. 如果没找到，检查历史记录
        if (!localPath) {
            const bookRecord = getDownloadHistory(bookId);
            if (bookRecord && bookRecord.episodes) {
                const episode = bookRecord.episodes.find(ep => ep.video_id === videoId);
                if (episode && episode.status === "success" && fm.fileExists(episode.path)) {
                    localPath = episode.path;
                }
            }
        }
     
    }
    
        // 最后尝试扫描文件系统
        if (!localPath) {
            const folders = fm.listContents(bookmarkPath);
            for (const folderName of folders) {
                if (!fm.isDirectory(fm.joinPath(bookmarkPath, folderName))) continue;
                
                const folderPath = fm.joinPath(bookmarkPath, folderName);
                const files = fm.listContents(folderPath);
                const videoFile = files.find(file => file.includes(`_${videoId}.mp4`));
                if (videoFile) {
                    localPath = fm.joinPath(folderPath, videoFile);
                    break;
                }
            }
        }
        if(localPath){
            let data = videoBase64String(localPath)
            console.log("查询本地缓存成功")
            sendSuccess(webView,callbackId,{pathData:data})
        }else{
            sendSuccess(webView,callbackId,{url:`${API_BASE}?video_id=${videoId}&type=mp4`})
        }
    }catch(e){
        console.log(`播放视频查询本地缓存失败${e}`)
        sendError(webView,callbackId,'-1',`播放视频查询本地缓存失败${e}`)
    }   
    // 打开视频
    //await showPlayOptions(videoId, localPath);
}

function videoBase64String(localPath){
    const fm = FileManager.local();
    const videoData = fm.read(localPath);
    // 3. 转换为 Base64
    const base64String = videoData.toBase64String();
    // 4. 生成 Data URL（H5可直接播放的格式）
    const dataURL = `data:video/mp4;base64,${base64String}`;
    
    return dataURL
}

// <---播放视频
async function showPlayOptions(videoId, localPath) {
    const alert = new Alert();
    alert.title = "播放选项";
    alert.message = `请选择播放方式：`;
    
    if (localPath) {
        // 如果有本地文件，优先显示本地播放选项
        alert.addAction("本地播放（更快）");
        alert.addAction("在线播放");
    } else {
        // 没有本地文件时只显示在线播放
        alert.addAction("在线播放");
    }
    alert.addCancelAction("取消");

    const selectedIndex = await alert.presentSheet();

    // 处理用户选择
    if (selectedIndex === -1) {
        // 用户点击了取消
        return;
    }

    if (localPath) {
        if (selectedIndex === 0) {
            // 本地播放
            Safari.open(`shareddocuments://${localPath}`);
        } else if (selectedIndex === 1) {
            // 在线播放
            Safari.open(`${API_BASE}?video_id=${videoId}&type=mp4`);
        }
    } else {
        if (selectedIndex === 0) {
            // 在线播放
            Safari.open(`${API_BASE}?video_id=${videoId}&type=mp4`);
        }
    }
}


//创建目录
function createBookmarkedFolder(name) {
    const fm = FileManager.local();
    let bookmarkPath = fm.bookmarkedPath("视频下载");
    if (!bookmarkPath) {
        bookmarkPath = fm.documentsDirectory();
    }
    
    const folderPath = fm.joinPath(bookmarkPath, name);
    if (!fm.isDirectory(folderPath)) {
        fm.createDirectory(folderPath);
    }
    return folderPath;
}

//获取下载历史
function getDownloadHistory(booId) {
    let history = KeyValueStore.get(booId+DOWNLOAD_HISTORY_KEY);
    if (history) {
        try {
            history = JSON.parse(history);
            if(downloadStatus[booId]){
                history.status = 'downloading'
            }else{
                history.status = 'completed'
            }
            return history
        } catch (e) {
            console.log("解析历史记录失败，尝试重建");
        }
    }
    // 2. 扫描文件系统重建历史记录
    history = rebuildDownloadHistory(booId);
    if(history){
        if(downloadStatus[booId]){
            history.status = 'downloading'
        }else{
            history.status = 'completed'
        }
    }else{
        history = {}
    }
    return history
}

// 扫描文件系统重建下载历史
function rebuildDownloadHistory(rebuildBooId) {
    let history = null;
    const folders = fm.listContents(bookmarkPath);
    
    for (const folderName of folders) {
        const folderFullPath = fm.joinPath(bookmarkPath, folderName);
        if (!fm.isDirectory(folderFullPath)) continue;
        
        // 检查文件夹名称格式：书籍名称_书籍ID
        const match = folderName.match(/^(.*)_(\d+)$/);
        if (!match) continue;
        
        const bookName = match[1];
        const bookId = match[2];
        
        if(bookId === rebuildBooId) {
            // 扫描文件夹中的文件
            const files = fm.listContents(folderFullPath);
            const videoFiles = files.filter(file => file.endsWith('.mp4'));
            
            // 重建记录
            const reconstructedRecord = {
                bookId: bookId,
                title: bookName,
                cover: "", // 封面无法重建
                download_date: "未知",
                total: videoFiles.length,
                success: videoFiles.length,
                failed: 0,
                status: "completed",
                episodes: [],
                category: "未知",
                desc:''
            };
            
            // 重建每一集的信息
            for (const fileName of videoFiles) {
                const filePath = fm.joinPath(folderFullPath, fileName);
                const fileSize = fm.fileSize(filePath);
                
                // 提取视频ID（假设文件名格式：标题_视频ID.mp4）
                const videoMatch = fileName.match(/(.*)_(\d+)\.mp4$/);
                let title = "未知标题";
                let videoId = "unknown";
                
                if (videoMatch) {
                    title = videoMatch[1];
                    videoId = videoMatch[2];
                }
                
                reconstructedRecord.episodes.push({
                    title: title,
                    video_id: videoId,
                    status: fileSize > 0 ? "success" : "failed",
                    path: filePath
                });
            }
            
            history = reconstructedRecord;
            break; // 找到目标后退出循环
        }
    }
    
    if(history) {
        // 保存重建的历史记录
        KeyValueStore.set(rebuildBooId + DOWNLOAD_HISTORY_KEY, JSON.stringify(history));
    }
    return history;
}

// 下载记录管理
function addDownloadHistory(item,booId) {
    if(item){
        KeyValueStore.set(booId+DOWNLOAD_HISTORY_KEY, JSON.stringify(item));
    }
}

//获取全部的下载历史
async function getAllDownloadHistory(webView,callbackId) {
    const folders = fm.listContents(bookmarkPath);
    let downloadHistory = [];
    try{
        folders.forEach(fileName => {
            const filePath = fm.joinPath(bookmarkPath, fileName);
            // 跳过目录
            if (fm.isDirectory(filePath)) return;
            
            // 检查文件名是否包含下载历史标识
            if (fileName.includes(DOWNLOAD_HISTORY_KEY)) {
                try {
                    // 读取文件内容
                    const fileData = fm.readString(filePath);
                    // 解析JSON数据
                    const historyItem = JSON.parse(fileData);
                    if(historyItem && historyItem.bookId){
                        if(!downloadStatus[historyItem.bookId]){
                            historyItem.status = 'completed'
                        }
                         downloadHistory.push(historyItem);
                    }
                    // 添加到结果数组
                } catch (error) {
                    console.error(`解析下载历史文件失败 ${fileName}: ${error}`);
                }
            }
        });
        sendSuccess(webView,callbackId,downloadHistory)
    }catch(e){
       console.error(`获取全部的下载历史失败: ${error}`);
    sendError(webView, callbackId, '-1', error.message);

    }
    return downloadHistory;
}

//删除视频
async function deleteBookVideos(webView, bookId,callbackId) {
    try {
        // 1. 获取下载历史记录以显示要删除的目录信息
        const bookRecord = getDownloadHistory(bookId);
        if (!bookRecord) {
            sendError(webView, callbackId, '-1', '未找到下载记录');
            return;
        }
        // 2. 创建确认弹窗
        const alert = new Alert();
        alert.title = "确认删除";
        alert.message = `确定要删除短剧《${bookRecord.title}》的所有下载文件吗？\n\n`;

        // 统一路径构造逻辑
        const folderName = `${bookRecord.title}_${bookId}`;
        let folderPath = fm.joinPath(bookmarkPath, folderName);

        alert.addAction("取消");
        alert.addDestructiveAction("确认删除");
        const response = await alert.presentSheet();
        // 3. 如果用户取消，直接返回
        if (response === -1 || response === 0) {
            console.log("用户取消了删除操作");
            return;
        }
        // 4. 执行删除操作
        console.log("开始删除书籍:", bookRecord.title);
        // 从下载状态中移除
        if (downloadStatus[bookId]) {
            delete downloadStatus[bookId];
        }
        // 删除本地文件
        let deletedFiles = 0;
        // 使用统一构造的folderPath
        if (fm.fileExists(folderPath)) {
            if (fm.isDirectory(folderPath)) {
                // 获取文件夹内所有内容（包括子目录）
                const allContents = fm.listContents(folderPath, true);
                deletedFiles = allContents.length;
                // 删除整个文件夹
                fm.remove(folderPath);
            } else {
                // 如果是文件直接删除
                fm.remove(folderPath);
                deletedFiles = 1;
            }
        }
        if(deletedFiles>0){
            // 5. 从历史记录中移除
            KeyValueStore.del(bookId+DOWNLOAD_HISTORY_KEY);
            sendSuccess(webView,callbackId,{"deletedFiles":deletedFiles})
        }
    } catch (error) {
        console.error(`删除视频失败: ${error}`);
        sendError(webView, callbackId, '-1', '删除视频失败');
    }
}

async function getCustomsInfo(webView, callbackId, data) {
    try {
        let customInfo = null;
        if (data && data.custom) {
            const customKey = data.custom;
            const storedData = KeyValueStore.get(customKey);
            if (storedData) {
                customInfo = JSON.parse(storedData);
            }
        }
        sendSuccess(webView, callbackId, {"info":customInfo});
    } catch (e) {
        console.error(`获取自定义信息失败: ${e}`);
        sendError(webView, callbackId, '-1', '获取自定义信息失败');
    }
}

async function addCustomInfo(webView, callbackId, data) {
    try {
        if (!data || !data.custom || data.value === undefined) {
            throw new Error('缺少必要参数: custom 或 value');
        }

        const customKey = data.custom;
        const newValue = data.value;
        const operation = data.operation || 'merge'; // 默认为合并操作
        
        // 获取现有数据
        const existingData = KeyValueStore.get(customKey);
        let finalValue = newValue;

        if (existingData) {
            const parsedExisting = JSON.parse(existingData);
            
            // 根据数据类型和操作类型决定如何合并数据
            if (operation === 'merge') {
                if (Array.isArray(parsedExisting) && Array.isArray(newValue)) {
                    // 数组合并（去重）
                    finalValue = [...new Set([...parsedExisting, ...newValue])];
                } else if (isPlainObject(parsedExisting) && isPlainObject(newValue)) {
                    // 对象合并（覆盖相同字段）
                    finalValue = {...parsedExisting, ...newValue};
                } else if (typeof parsedExisting === typeof newValue) {
                    // 相同基本类型直接覆盖
                    finalValue = newValue;
                } else {
                    // 类型不匹配时覆盖
                    console.warn(`数据类型不匹配，将覆盖原有数据。Key: ${customKey}`);
                }
            } else if (operation === 'replace') {
                // 直接覆盖
                finalValue = newValue;
            } else if (operation === 'append' && Array.isArray(parsedExisting)) {
                // 数组追加
                finalValue = [...parsedExisting, newValue];
            }
        }
        // 存储最终值
        KeyValueStore.set(customKey, JSON.stringify(finalValue));
        sendSuccess(webView, callbackId, {status: 'success', operation});
    } catch (e) {
        console.error(`添加自定义信息失败: ${e}`);
        sendError(webView, callbackId, '-2', `添加失败: ${e.message}`);
    }
}

function isPlainObject(obj) {
    return typeof obj === 'object' && 
           obj !== null && 
           obj.constructor === Object;
}


//下载记录存储json
const KeyValueStore = {
    set: function(key, value) {
        const path = this.getFilePath(key);
        fm.writeString(path, value);
    },
    
    get: function(key) {
        const path = this.getFilePath(key);
        if (fm.fileExists(path)) {
            return fm.readString(path);
        }
        return null;
    },
    del:function(key) {
        const path = this.getFilePath(key);
        if (fm.fileExists(path)) {
            return fm.remove(path);
        }
        return null;
    },
    
    getFilePath: function(key) {
        // 文件名使用 key 的哈希避免非法字符
        const fileName = `kv_${key}.json`;
        return fm.joinPath(bookmarkPath, fileName);
    }
};

// await main();
// Script.complete();
